package com.minisoft.workhour.client;

import com.alibaba.fastjson.JSON;
import com.minisoft.workhour.config.ApiConfig;
import com.minisoft.workhour.model.ManhourRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 工时API客户端
 */
@Slf4j
public class ManhourApiClient {
    
    /**
     * 提交工时记录
     */
    public boolean submitManhour(ManhourRequest request) {
        try {
            URL url = new URL(ApiConfig.MANHOUR_API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法
            connection.setRequestMethod("POST");
            
            // 设置请求头
            connection.setRequestProperty("Cookie", ApiConfig.COOKIE);
            connection.setRequestProperty("User-Agent", ApiConfig.USER_AGENT);
            connection.setRequestProperty("Content-Type", ApiConfig.CONTENT_TYPE);
            connection.setRequestProperty("Accept", ApiConfig.ACCEPT);
            connection.setRequestProperty("Host", ApiConfig.HOST);
            connection.setRequestProperty("Connection", ApiConfig.CONNECTION);
            
            // 启用输出
            connection.setDoOutput(true);
            
            // 准备请求体
            String jsonBody = JSON.toJSONString(request);
            log.info("发送请求: {}", jsonBody);
            
            // 写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            
            // 获取响应
            int responseCode = connection.getResponseCode();
            log.info("响应状态码: {}", responseCode);
            
            // 读取响应内容
            StringBuilder response = new StringBuilder();
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            responseCode >= 200 && responseCode < 300 
                                ? connection.getInputStream() 
                                : connection.getErrorStream(), 
                            StandardCharsets.UTF_8))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            }
            
            String responseBody = response.toString();
            log.info("响应内容: {}", responseBody);
            
            // 判断是否成功
            boolean success = responseCode >= 200 && responseCode < 300;
            if (success) {
                log.info("工时提交成功");
            } else {
                log.error("工时提交失败，状态码: {}, 响应: {}", responseCode, responseBody);
            }
            
            return success;
            
        } catch (IOException e) {
            log.error("提交工时时发生异常", e);
            return false;
        }
    }
    
    /**
     * 批量提交工时记录（每次提交一个）
     */
    public int batchSubmitManhour(ManhourRequest request) {
        if (request.getManhours() == null || request.getManhours().isEmpty()) {
            log.warn("没有工时记录需要提交");
            return 0;
        }
        
        int successCount = 0;
        
        // 逐个提交工时记录
        for (ManhourRequest.ManhourItem manhourItem : request.getManhours()) {
            ManhourRequest singleRequest = new ManhourRequest();
            singleRequest.setManhours(java.util.Collections.singletonList(manhourItem));
            
            log.info("提交工时记录: {} - {} - {}小时", 
                    manhourItem.getDescription(), 
                    manhourItem.getTask(), 
                    manhourItem.getHours() / 100000.0);
            
            if (submitManhour(singleRequest)) {
                successCount++;
                log.info("工时记录提交成功");
            } else {
                log.error("工时记录提交失败");
            }
            
            // 添加延迟避免请求过快
            try {
                Thread.sleep(1000); // 1秒延迟
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("线程被中断");
                break;
            }
        }
        
        log.info("批量提交完成，成功: {}/{}", successCount, request.getManhours().size());
        return successCount;
    }
}
